package com.markyao.service.impl;

import com.markyao.recos.regist.RecosRegistConfig;
import com.markyao.service.AuthService;
import com.markyao.handler.JwtHandler;
import com.markyao.utils.MD5Util;
import com.markyao.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class AuthServiceImpl implements AuthService {
    @Autowired(required = false)
    @Qualifier("recosRegistConfig")
    RecosRegistConfig recosRegistConfig;

    @Autowired(required = false)
    @Qualifier("recvThreshold")
    AtomicInteger recvThreshold;

    @Autowired
    JwtHandler jwtHandler;
    private final static Set<String>adsSet=new HashSet<>();
    @Override
    public Result auth(String username, String password) {
        String token = getToken(username, password);
        if (token!=null){
            return Result.success("验证成功",token);
        }

        return Result.failed(555,"校验失败!!!");
    }

    @Override
    public String authing(String username, String password) {
        return getToken(username, password);
    }


    @Override
    public Result auth0(String username, String password, String targetAddress) {
        synchronized (adsSet){
            if (!adsSet.contains(targetAddress)){
                String token = getToken(username, password);
                if (token!=null){
                    if (recvThreshold==null){
                        System.out.println("注入失败...");
                    }
                    adsSet.add(targetAddress);
                    recvThreshold.decrementAndGet();
                    return Result.success("验证成功",token);
                }
                return Result.success("校验失败!!!");
            }else {
                return Result.failed(777,"重复验证");
            }

        }

    }

    @Override
    public String getToken(String username, String password) {
        String unMd5 = MD5Util.string2MD5(username);
        String pdwMd5 = MD5Util.string2MD5(password);
        boolean b = unMd5.equals(recosRegistConfig.getUsernameMD5()) && pdwMd5.equals(recosRegistConfig.getPasswordMD5());
        if (b){
            String token= jwtHandler.createToken(username,password);
            return token;
        }
        return null;
    }

    @Override
    public boolean checkToken(String token) {
        if (token==null || !StringUtils.hasText(token)){
            return false;
        }
        Map<String, Object> map = jwtHandler.checkToken(token);
        return map!=null;
    }


}
